package com.heima.leetcode.practice;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 236. 二叉树的最近公共祖先
 * @date 2025/2/10 0:27
 */
public class E236 {

    /**
     * 递归解法
     *
     * @param root 根节点
     * @param p    节点p
     * @param q    节点q
     * @return 最近公共祖先节点
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) return root;
        // 求出左子树的最近公共祖先节点或者pq某一个节点
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        // 求出右子树的最近公共祖先节点或者pq某一个节点
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) return root;
        else if (left != null) return left;
        else if (right != null) return right;
        else return null;
    }
}
